package com.ti.winona.ui;

import org.json.JSONObject;

import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.taplinker.client.App;
import com.taplinker.client.AppConfigFactory;
import com.taplinker.client.R;
import com.taplinker.client.core.LocalFileManager;
import com.taplinker.client.domain.UserInfo;
import com.taplinker.client.im.SocketTemplateContext;
import com.taplinker.client.im.rpc.Cmd002;
import com.taplinker.core.rpc.RpcClientContext;
import com.taplinker.core.util.json.JsonUtil;
import com.ti.winona.ConstantValue;
import com.ti.winona.bean.User;
import com.ti.winona.net.API;
import com.ti.winona.net.RequestClient;
import com.ti.winona.util.SharedPreferencesUtil;
import com.ti.winona.widget.LoadingDialog;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

@SuppressLint("HandlerLeak")
public class WelcomeActivity extends Activity {
	
	private LoadingDialog mLoadingDialog;
	
	private String mUserName;
	private String mPassWord;
	
	private Handler myHandler = new Handler(){

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			// 跳转到登录界面
			startActivity(new Intent(WelcomeActivity.this, LoginActivity.class));
			finish();
		}
		
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_welcome);
		
		autoLogin();
	}
	
	private void initDialog() {
		mLoadingDialog = new LoadingDialog(this);
		mLoadingDialog.setText("自动登录中...");
		mLoadingDialog.setCancelable(true);
		mLoadingDialog.setCanceledOnTouchOutside(false);
	}
	
	private void autoLogin() {
		mUserName = SharedPreferencesUtil.getString(this, ConstantValue.sharedpreferences.SHARED_NAME, ConstantValue.sharedpreferences.USER_NAME);
		mPassWord = SharedPreferencesUtil.getString(this, ConstantValue.sharedpreferences.SHARED_NAME, ConstantValue.sharedpreferences.USER_PASSWORD);
		if( mUserName != null && mPassWord != null && !"".equals(mUserName) && !"".equals(mPassWord) ) {
			initDialog();
			httpLogin();
		}else{
			// 延时跳转到登录界面
			new Thread(new Runnable() {
				
				@Override
				public void run() {
					try {
						Thread.sleep(2000);
						myHandler.sendEmptyMessage(0);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}).start();
			
		}
	}
	
	// 自动登陆
	private void httpLogin() {
		
		RequestParams params = new RequestParams();
		params.put("body.username", mUserName);
		params.put("body.password", mPassWord);
		params.put("from", "EXPERT");
		
		RequestClient.post(this, API.HTTP_LOGIN, params, new AsyncHttpResponseHandler(){

			@Override
			public void onStart() {
				super.onStart();
				mLoadingDialog.show();
			}
			
			@Override
			public void onFailure(Throwable error, String content) {
				super.onFailure(error, content);
				mLoadingDialog.dismiss();
				App.showLog("log_ktian", "http-login_welcome-Failure");
				App.showToast("自动登录失败");
				// 跳转到登录界面
				myHandler.sendEmptyMessage(0);
			}

			@Override
			public void onSuccess(String content) {
				super.onSuccess(content);
				App.showLog("log_ktian", "http-login_welcome-Success");
				try {
					JSONObject jsonObject = new JSONObject(content);
					if("OK".equalsIgnoreCase(jsonObject.getString("code"))) {
						
						User user = JsonUtil.jsonToObject(jsonObject.getString("body"), User.class);
						
						UserInfo userInfo = new UserInfo();
						userInfo.setUserName(user.getExpert().getUsername());
						userInfo.setUserIcon(user.getExpert().getHead());
						userInfo.setId(Long.valueOf(user.getExpert().getId()));
						userInfo.setUserid(Long.valueOf(user.getExpert().getUserid()));
						userInfo.setNickname(user.getExpert().getName());
						
						userInfo.setToken(user.getToken());
						userInfo.setImToken(user.getToken());
						
//						Expert expert = new Expert();
//						expert.setHead(user.getExpert().getHead());
//						expert.setPhysicianCertificate(user.getExpert().getPhysicianCertificate());
//						expert.setIdentification(user.getExpert().getIdentification());
//						expert.setPosition(user.getExpert().getPosition());
//						expert.setPhone(user.getExpert().getPhone());
//						expert.setMail(user.getExpert().getMail());
//						expert.setSexual(user.getExpert().getSexual());
//						expert.setId(user.getExpert().getId());

						AppConfigFactory.getInstance().setAppKey("19581e27de7ced00ff1ce50b2047e7a567c76b1cbaebabe5ef03f7c3017bb5b7");
						AppConfigFactory.getInstance().setUserInfo(userInfo);
						AppConfigFactory.getInstance().setUser(user);
						
						LocalFileManager.getInstance().ayscCreateDirs();
						RpcClientContext.getInstance().setCookies("TAPLINKER_TOKEN=" + user.getToken());
						SocketTemplateContext.getInstance().initialize(WelcomeActivity.this);
						
						// 开始Taplinker登陆
						new Cmd002(WelcomeActivity.this, mLoadingDialog).execute();
						
					}else{
						App.showToast(jsonObject.getString("message"));
						onFailure(null, "http登录code为FAILED");
					}
				} catch (Exception e) {
					e.printStackTrace();
					onFailure(null, "http登陆解析出错");
				}
				
			}
			
		});
	}
	
}
